package ai.restosuite.infrastructure.action;

import ai.restosuite.infrastructure.GitFlowPlus;
import ai.restosuite.infrastructure.i18n.I18n;
import ai.restosuite.infrastructure.i18n.I18nKey;
import ai.restosuite.infrastructure.ui.MergeRequestDialog;
import ai.restosuite.infrastructure.utils.CollectionUtils;
import ai.restosuite.infrastructure.utils.ConfigUtil;
import ai.restosuite.infrastructure.utils.GitBranchUtil;
import ai.restosuite.infrastructure.utils.NotifyUtil;
import ai.restosuite.infrastructure.valve.merge.Valve;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.ReflectionUtil;
import git4idea.commands.GitCommandResult;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Objects;

/**
 * merge request
 *
 * @author yuhao.wang3
 */
public class MergeRequestAction extends AbstractMergeAction {
    protected GitFlowPlus gitFlowPlus = GitFlowPlus.getInstance();

    public MergeRequestAction() {
        super("Merge Request", "发起 code review", IconLoader.getIcon("/icons/mergeToTest.svg", Objects.requireNonNull(ReflectionUtil.getGrandCallerClass())));
    }

    @Override
    protected void setEnabledAndText(AnActionEvent event) {
        event.getPresentation().setText(I18n.getContent(I18nKey.MERGE_REQUEST_ACTION$TEXT));
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        Project project = event.getProject();
        final String currentBranch = gitFlowPlus.getCurrentBranch(project);
        final String targetBranch = ConfigUtil.getConfig(project).get().getTestBranch();
        final GitRepository repository = GitBranchUtil.getCurrentRepository(project);
        if (Objects.isNull(repository)) {
            return;
        }

        GitCommandResult result = gitFlowPlus.getLocalLastCommit(repository, currentBranch);
        String[] msgs = result.getOutputAsJoinedString().split("-body:");
        MergeRequestDialog mergeRequestDialog = new MergeRequestDialog(project, msgs[0], msgs[1]);
        mergeRequestDialog.show();
        if (!mergeRequestDialog.isOK()) {
            return;
        }


        new Task.Backgroundable(project, "Merge Request", false) {
            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                NotifyUtil.notifyGitCommand(event.getProject(), "===================================================================================");

                String tempBranchName = currentBranch + "_temp";
                // 删除分支
                GitCommandResult result = gitFlowPlus.deleteBranch(repository, currentBranch, tempBranchName);
                // 新建分支
                result = gitFlowPlus.newNewBranchByLocalBranch(repository, currentBranch, tempBranchName);
                if (!result.success()) {
                    NotifyUtil.notifyError(project, "Error", result.getErrorOutputAsJoinedString());
                    return;
                }
                // 发起merge request
                result = gitFlowPlus.mergeRequest(repository, tempBranchName, targetBranch, mergeRequestDialog.getMergeRequestOptions());
                if (!result.success()) {
                    NotifyUtil.notifyError(project, "Error", result.getErrorOutputAsJoinedString());
                }
                NotifyUtil.notifySuccess(project, "Success", result.getErrorOutputAsHtmlString());
                if (CollectionUtils.isNotEmpty(result.getErrorOutput()) && result.getErrorOutput().size() > 3) {
                    String address = result.getErrorOutput().get(2);
                    address = address.split("   ")[1];
                    BrowserUtil.browse(address);
                }
                // 删除本地临时分支
                result = gitFlowPlus.deleteLocalBranch(repository, currentBranch, tempBranchName);
                if (!result.success()) {
                    NotifyUtil.notifyError(project, "Error", result.getErrorOutputAsJoinedString());
                }
                // 刷新
                repository.update();
                myProject.getMessageBus().syncPublisher(GitRepository.GIT_REPO_CHANGE).repositoryChanged(repository);
                VirtualFileManager.getInstance().asyncRefresh(null);
            }
        }.queue();
    }

    @Override
    protected String getTargetBranch(Project project) {
        return null;
    }

    @Override
    protected String getDialogTitle(Project project) {
        return null;
    }

    @Override
    protected String getTaskTitle(Project project) {
        return null;
    }

    @Override
    protected List<Valve> getValves() {
        return null;
    }


}



